;$(function(){
	$('#optDiv').find('a').each(function(i, element) {
		var $element = $(element);
		var index = parseInt($(element).attr('data-index'));
		if (13 === index) {
			$element.addClass('on');
		} else {
			$element.removeClass('on');
		}
	});
	var name = window.getUrl.geturlset('username');
	if(name){
		$('.head #selectState').hide();
		$('.head div.timer').hide();
		$('.head div.sep').hide();
		$('.head button').hide();
		$("#faEmail").css('background','#ecceb1');
		$('#shouEmail').css('background','#ecceb1');
		$('#wirteEmail').css('background','#f5f0e7');
		$("#findEmail").fadeOut();
		$("#emailDetail").fadeOut(function(){
			$("#wirteE").fadeIn();
			$("#agentsjr").find('label').hide();
			$("#agentsjr").find('label input').attr('checked',false);
			$("#agentsjr").find('div').html(name);
		});
	}else{
		$("#emailDetail").fadeIn();
		$("#shouEmail").css('background','#f5f0e7');
	}
	$("#sixin").find('.cs-placeholder').click(function(){
		$("#sixin").addClass("cs-active");
	});
	$("#shouEmail").click(function(){
		$('.head #selectState').show();
		$('.head div.timer').show();
		$('.head div.sep').show();
		$('.head button').show();
		$('#emailDetail table tbody').remove();
		$('#queryToMessage').show();
		$('#queryFromMessage').hide();
		$("#faEmail").css('background','#ecceb1');
		$('#wirteEmail').css('background','#ecceb1');
		$(this).css('background','#f5f0e7');
		$("#wirteE").fadeOut(function(){
			$("#emailDetail").fadeIn();
			$("#findEmail").fadeIn();
		});
	});
	$("#faEmail").click(function(){
		$('.head #selectState').show();
		$('.head div.timer').show();
		$('.head div.sep').show();
		$('.head button').show();
		$('#emailDetail table tbody').remove();
		$('#queryToMessage').hide();
		$('#queryFromMessage').show();
		$("#shouEmail").css('background','#ecceb1');
		$('#wirteEmail').css('background','#ecceb1');
		$(this).css('background','#f5f0e7');
		$("#wirteE").fadeOut(function(){
			$("#emailDetail").fadeIn();
			$("#findEmail").fadeIn();
		});
	});
	$("#wirteEmail").click(function(){
		$('.head #selectState').hide();
		$('.head div.timer').hide();
		$('.head div.sep').hide();
		$('.head button').hide();
		$("#faEmail").css('background','#ecceb1');
		$('#shouEmail').css('background','#ecceb1');
		$(this).css('background','#f5f0e7');
		$("#findEmail").fadeOut();
		$("#emailDetail").fadeOut(function(){
			$("#wirteE").fadeIn();
		});

		$.ajax({
			type: 'POST',
			url: window._commonURL + '/rest/user/queryAgentPlayer',
			data: {
				isDirect: 'Y'
			},
			dataType: 'json',
			async: true,
			success: function(response) {
				console.log(response);
				if (response && response.status === '00') {
					$('#parent').after('<input id="toUser" type="hidden" />');
					$('#toUser').val(response.userCode);
				} else {
					if ('没有上级代理' === response.errorMsg) {
						$('#parent').parent().hide();
					}
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				console.log(XMLHttpRequest);
				console.log(textStatus);
				console.log(errorThrown);
			},
			complete: function(XMLHttpRequest, textStatus) {
				console.log(XMLHttpRequest),
				console.log(textStatus);
			}
		});
	});

	$('#sendMessage').on('click', function() {
		var toUser;
		if ($('#children').attr('checked')) {
			$('#userInfo').children('option').each(function(index, element) {
				if ($(this).text() === $('#toUserInfo').val()) {
					toUser = $(this).attr('id');
				}
			})
		} else if ($('#parent').attr('checked')) {
			toUser = $('#toUser').val();
		}else{
			toUser = $("#oneChildren").val();
		}
		var title = $('#title').val();
		var content = $('#content').val();
		if (!title || !$.trim(title)) {
			window.alert('标题不能为空');
			return false;
		}
		if (!content || !$.trim(content)) {
			window.alert('内容不能为空');
			return false;
		}
		if ($('#children').attr('checked') && !toUser) {
			window.alert('收件人不能为空');
			return false;
		}
		$(this).attr('disabled', true);
		$.ajax({
			type: 'POST',
			url: window._commonURL + '/rest/message/saveMessage',
			data: {
				messageTitle: title,
				messageContent: content,
				messageState: '01',
				receiveUserCode: toUser
			},
			dataType: 'json',
			async: true,
			success: function(response) {
				console.log(response);
				if (response && response.status === '00') {
					window.alert('发送成功');
					$('#title').val('');
					$('#content').val('');
				} else {
					window.alert(response.errorMsg);
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				console.log(XMLHttpRequest);
				console.log(textStatus);
				console.log(errorThrown);
			},
			complete: function(XMLHttpRequest, textStatus) {
				console.log(XMLHttpRequest),
				console.log(textStatus);
				$('#sendMessage').removeAttr('disabled');
			}
		});
	});

	$('#queryFromMessage').on('click', function() {
		$('#selectState').show();
		$('#emailDetail thead tr').remove();
		$('#emailDetail thead').append('<tr class="title"><td>主题</td><td>收件人</td><td>状态</td><td>时间</td><td>操作</td></tr>');
		var stateCodes = [, '01', '02'];
		var stateMsgs = ['所有', '未读', '已读'];
		var state = $('#sixin span.cs-placeholder').text();
		var fromDate = $('#datetimepicker_fromTime').val();
		var toDate = $('#datetimepicker_toTime').val();
		if (fromDate > toDate) {
			window.alert('起始时间大于结束时间');
			return false;
		}
		var param = {
			flag: '00',
			messageState: stateCodes[stateMsgs.indexOf(state)],
			beginDate: fromDate + ':00',
			endDate: toDate + ':00'
		}
		$.ajax({
			type: 'POST',
			url: window._commonURL + '/rest/message/queryMessages',
			data: param,
			dataType: 'json',
			async: true,
			success: function(response) {
				console.log(response);
				if (response && response.status === '00') {
					$('#emailDetail table tbody').remove();
					sessionStorage.clear();
					window.cacheUtil.clearCookie();
					var length = response.messageList && response.messageList.length;
					var tbody = '<tbody>';
					for (var index = 0; index < length; index++) {
						sessionStorage.setItem(response.messageList[index].messageId, JSON.stringify(response.messageList[index]));
						window.cacheUtil.setCookie(response.messageList[index].messageId, JSON.stringify(response.messageList[index]));
						var tr = '<tr id=' + response.messageList[index].messageId + '>' + 
								 '<td><a onclick="showContent(' + response.messageList[index].messageId + ')">' + response.messageList[index].messageTitle + '</a></td>' +
								 '<td>' + response.messageList[index].receiveUserCode + '</td>' +
								 '<td class="state"><span class="red">' + stateMsgs[+response.messageList[index].messageState] + '</span></td>' +
								 '<td>' + new Date(response.messageList[index].createDate) + '</td>' +
								 '<td><button onclick="deleteMessage(' + response.messageList[index].messageId + ')">删除</button></td>' +
								 '</tr>';
						tbody += tr;
					}
					tbody += '</tbody>';
					$('#emailDetail table').append(tbody);
				} else {
					window.alert(response.errorMsg);
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				console.log(XMLHttpRequest);
				console.log(textStatus);
				console.log(errorThrown);
			},
			complete: function(XMLHttpRequest, textStatus) {
				console.log(XMLHttpRequest),
				console.log(textStatus);
			}
		});
	});

	$('#queryToMessage').on('click', function() {
		$('#selectState').hide();
		$('#emailDetail thead tr').remove();
		$('#emailDetail thead').append('<tr class="title"><td>主题</td><td>发件人</td><td>状态</td><td>时间</td></tr>');
		var stateCodes = [, '01', '02'];
		var stateMsgs = ['所有', '未读', '已读'];
		var state = $('#sixin span.cs-placeholder').text();
		var fromDate = $('#datetimepicker_fromTime').val();
		var toDate = $('#datetimepicker_toTime').val();
		if (fromDate > toDate) {
			window.alert('起始时间大于结束时间');
			return false;
		}
		var param = {
			flag: '01',
			messageState: stateCodes[stateMsgs.indexOf(state)],
			beginDate: fromDate + ':00',
			endDate: toDate + ':00'
		}
		$.ajax({
			type: 'POST',
			url: window._commonURL + '/rest/message/queryMessages',
			data: param,
			dataType: 'json',
			async: true,
			success: function(response) {
				console.log(response);
				if (response && response.status === '00') {
					$('#emailDetail table tbody').remove();
					sessionStorage.clear();
					window.cacheUtil.clearCookie();
					var length = response.messageList && response.messageList.length;
					var tbody = '<tbody>';
					for (var index = 0; index < length; index++) {
						sessionStorage.setItem(response.messageList[index].messageId, JSON.stringify(response.messageList[index]));
						window.cacheUtil.setCookie(response.messageList[index].messageId, JSON.stringify(response.messageList[index]));
						var tr = '<tr id=' + response.messageList[index].messageId + '>' + 
								 '<td><a onclick="showToMessage(' + response.messageList[index].messageId + ')">' + response.messageList[index].messageTitle + '</a></td>' +
								 '<td>' + response.messageList[index].sendUserCode + '</td>' +
								 '<td class="state"><span class="red">' + stateMsgs[+response.messageList[index].messageState] + '</span></td>' +
								 '<td>' + new Date(response.messageList[index].createDate) + '</td>' +
								 '</tr>';
						tbody += tr;
					}
					tbody += '</tbody>';
					$('#emailDetail table').append(tbody);
				} else {
					window.alert(response.errorMsg);
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				console.log(XMLHttpRequest);
				console.log(textStatus);
				console.log(errorThrown);
			},
			complete: function(XMLHttpRequest, textStatus) {
				console.log(XMLHttpRequest),
				console.log(textStatus);
			}
		});
	});

	(function() {
		$.ajax({
			type: 'POST',
			url: window._commonURL + '/rest/user/queryUsers',
			data: {},
			dataType: 'json',
			async: true,
			success: function(response) {
				console.log(response);
				if (response && response.status === '00') {
					var length = response.userList.length;
					var dataList = '<datalist id="userInfo" style="display: none;">'
					for (var index = 0; index < length; index++) {
						var option = '<option id="' + response.userList[index].userCode 
									+ '" data-role="' + response.userList[index].role + '">'
									+ response.userList[index].userName + '</option>';
						dataList += option;
					}
					dataList += '</datalist>';
					$('#toUserInfo').after(dataList);
				} else {
					
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				console.log(XMLHttpRequest);
				console.log(textStatus);
				console.log(errorThrown);
			},
			complete: function(XMLHttpRequest, textStatus) {
				console.log(XMLHttpRequest),
				console.log(textStatus);
			}
		});
	})();

	$('#children').on('click', function() {
		$('#parent').removeAttr('checked');
		$('#toUserInfo').show();
		$('#userInfo').show();
	});

	$('#parent').on('click', function() {
		$('#children').removeAttr('checked');
		$('#toUserInfo').hide();
		$('#userInfo').hide();

	});

});
;function modelFun(e){
	var e=window.event||e;
	e = e.srcElement||e.target; 
	if(e.nodeName == 'SPAN'){
		var val = $(e).parent().attr('data-value');
		var text = $(e).text();
		$("#sixin").attr('data-index',val);
		$("#sixin").find('.cs-placeholder').text(text);
	};
	$("#sixin").removeClass('cs-active');
};

function deleteMessage(messageId) {
	$.ajax({
		type: 'POST',
		url: window._commonURL + '/rest/message/deleteMessage',
		data: {messageId: messageId},
		dataType: 'json',
		async: true,
		success: function(response) {
			console.log(response);
			if (response && response.status === '00') {
				window.alert('删除成功');
				$('#' + messageId + '').remove();
			} else {
				window.alert(response.errorMsg);
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			console.log(XMLHttpRequest);
			console.log(textStatus);
			console.log(errorThrown);
		},
		complete: function(XMLHttpRequest, textStatus) {
			console.log(XMLHttpRequest),
			console.log(textStatus);
		}
	});
}

function showToMessage(messageId) {
	var message = sessionStorage.getItem(messageId) && JSON.parse(sessionStorage.getItem(messageId)) || window.cacheUtil.getCookie(messageId) && JSON.parse(window.cacheUtil.getCookie(messageId));
	var messageState = message.messageState || '';
	var messageContent =message.messageContent || '';
	if ('01' === messageState) {
		var param = {
			messageState: '02'
		}
		$.ajax({
			type: 'POST',
			url: window._commonURL + '/rest/message/updateMessage',
			data: param,
			dataType: 'json',
			async: true,
			success: function(response) {
				console.log(response);
				if (response && response.status === '00') {
					$('#' + messageId + ' span.red').text('已读');
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				console.log(XMLHttpRequest);
				console.log(textStatus);
				console.log(errorThrown);
			},
			complete: function(XMLHttpRequest, textStatus) {
				console.log(XMLHttpRequest),
				console.log(textStatus);
			}
		});
	}
	showContent(messageId);
}

function showContent(messageId) {
	var message = sessionStorage.getItem(messageId) && JSON.parse(sessionStorage.getItem(messageId)) || window.cacheUtil.getCookie(messageId) && JSON.parse(window.cacheUtil.getCookie(messageId));
	var messageContent =message.messageContent || '';
	showDialog({body: '<div class="dialogue-icon error icon-attention-alt"></div><div class="dialogue-text">' + messageContent + '</div>',
										time: 60,
										okBtn: '确定'});
}

function showDialog(param) {
	if (param) {
		$('.dialogue-body').html(param.body);
		if (param.time) {
			showLeftTime(+param.time);
		}
		if (param.okBtn) {
			$('.dialogue-yes').html(param.okBtn).show().on('click', function() {
				$('#dialogue').hide();
				window.clearTimeout(window.timeout);
			});
		} else {
			$('.dialogue-yes').hide();
		}
		if (param.noBtn) {
			$('.dialogue-no').html(param.noBtn).show().on('click', function() {
				$('#dialogue').hide();
				window.clearTimeout(window.timeout);
			});
		} else {
			$('.dialogue-no').hide();
		}
		$('#dialogue').show();
	}
}

function showLeftTime(time) {
	$('.dialogue-sec').html(time);
	if (time-- < 0) {
		$('#dialogue').hide();
		return false;
	}
	window.timeout = window.setTimeout(function() {
		showLeftTime(time);
	}, 1000);
}